/*
 * SimpleTest.java
 *
 * Created on 30 november 2005, 14:43
 */

package org.pereni.ctrl.demo;

import java.util.Timer;
import java.util.TimerTask;
import javax.comm.SerialPort;
import org.pereni.ctrl.DataImp;
import org.pereni.ctrl.Device;
import org.pereni.ctrl.DeviceImp;
import org.pereni.ctrl.DeviceRegister;
import org.pereni.ctrl.DeviceRegisterImp;
import org.pereni.ctrl.comm.ComControl;
import org.pereni.ctrl.comm.ComHandler;
import org.pereni.ctrl.comm.SerialComHandler;
import org.pereni.ctrl.comm.SerialParameters;
//import org.pereni.ctrl.vend.omron.fins.command.MemmoryRead;
import org.pereni.ctrl.vend.omron.toolbus.ToolbusProtocol;
import org.pereni.ctrl.vend.omron.toolbus.commands.AreaReadDM;
import org.pereni.ctrl.vend.omron.toolbus.commands.MemoryRead;

/**
 *
 * @author  JanCarel
 */
public class SimpleTest extends javax.swing.JFrame {
  
  /** Creates new form SimpleTest */
  public SimpleTest() {
    initSystem();
    initComponents();
    setTitle("First communications test with Omron PLC");
    setSize(800,800);
  }
  
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 400, Short.MAX_VALUE)
                );
        layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 300, Short.MAX_VALUE)
                );
        pack();
    }
    // </editor-fold>//GEN-END:initComponents
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
          new SimpleTest().setVisible(true);
        }
      });
    }
    
    public void initSystem(){
      plc = new DeviceImp(0, "CQM1", "Test PLC", "PLC for communications test");
      
      deviceRegister = DeviceRegisterImp.getInstance();
      deviceRegister.addDevice(plc);
      
      
      
      comHandler = new SerialComHandler(getPLCSerialParameters(), "PLCCON");
      
      if( comHandler instanceof ComControl) {
        ((ComControl)comHandler).setCommunicationTimeOut(10000);
      }
      comHandler.initialize();
      comHandler.setProtocolHandler(new ToolbusProtocol());
      comHandler.start();
      
      if(comHandler.isStarted()){
      //dataRead = new MemmoryRead(MemmoryRead.DM_WORD, 0, 10);
      //readData = new FinsProxy(plc, dataRead);
      readData = new AreaReadDM(plc, 0,20);
      Timer pingTimer = new Timer();
      pingTimer.schedule(new PingTask(), 1000 , 100 );
      }else{
        //no good without com port, show error
      }
    }
    
    public SerialParameters getPLCSerialParameters() {
      SerialParameters parameters = new SerialParameters();
      parameters.setPortName("COM4");
      //getLog().info("PLC Connecting on port: " + comPort);
      parameters.setBaudRate(19200);
      //getLog().info("PLC Connecting at speed: " + comSpeed);
      parameters.setParity(SerialPort.PARITY_EVEN);
      //getLog().info("PLC Parity: " + parameters.getParityString());
      parameters.setDatabits(SerialPort.DATABITS_7);
      //getLog().info("PLC Data Bits: " + parameters.getDatabitsString());
      parameters.setStopbits(SerialPort.STOPBITS_2);
      //getLog().info("PLC Stop Bits: " + parameters.getStopbitsString());
      return parameters;
    }
    
    
    class PingTask extends TimerTask {
      public void run() {
        // dataRead.clear();
        long startT = System.currentTimeMillis();
        comHandler.send(readData);
        
        //int[]dataBuff =dataRead.getReply().toIntArray();
        
        int[]dataBuff =readData.getReply().toIntArray();
        //   System.out.println("reply length is "+dataBuff.length+"/"+dataRead.getLength());
        System.out.println(" took time :: "+(System.currentTimeMillis()-startT));
        DataImp di = new DataImp(dataBuff);
        
        System.out.println(" data inp is "+di.toString());
        
      }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    //protected String        comPort = "COM3";
    //protected int          comSpeed = 57600;
    //protected boolean   updateOnMin = true;
    protected SerialComHandler comHandler = null;
    protected Device            plc = null;
    protected DeviceRegister deviceRegister;
    // protected FinsProxy  readData;
    protected AreaReadDM readData;
    protected MemoryRead  dataRead;
}
